package ThreadDemo.ThreadDemo5;

import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:周次煜
 * Date: 2024-07-21
 * Time：21:30
 */
public class ThreadDemo1 {

   public static int sum1= 0,sum2=0;
   public static int [] nums = new int[1000_0000];

    public static void main(String[] args) throws InterruptedException {
      long start =  System.currentTimeMillis();
        Random r = new Random();

        for (int i = 0; i <1000_0000 ; i++) {
            nums[i]= r.nextInt(100)+1;
        }

        Thread t1 = new Thread(()-> {
            synchronized(ThreadDemo1.class) {
                for (int i = 0; i < 10000000; i+= 2) {
                    sum1 += nums[i];
                }
            }

        });


        Thread t2= new Thread(()->{
            synchronized(ThreadDemo1.class) {
                for (int i = 1; i < 10000000; i += 2) {
                    sum2 += nums[i];
                }
            }
        });

        t1.start();
        t2.start();


        t1.join();
        t2.join();

        long end = System.currentTimeMillis();

        System.out.println("偶数下标和： "+sum1 + " 奇数下标和： "+ sum2+ " 总和为： " + (sum1 + sum2));

        System.out.println("总耗时： "+ (end - start) );
    }
}
